import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Input, Spin, Typography, Tooltip } from 'antd';
import { SearchOutlined, DeleteOutlined } from '@ant-design/icons';
import HeaderLogo from '@/pages/components/logo';
import HomeMenuList from '@/pages/components/menus/HomeMenuList';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);
dayjs.extend(timezone);
import chatService from '@/api/services/chatService';
import { useConfig, useConfigActions } from '@/store/configStore';
import { useRouter } from '@/router/hooks';
import useWindowWidth from '@/hooks/event/use-window-width';

import { removeRefTags } from '@/utils/regexRules';
import { debounce } from 'lodash';

import './styles/history.css';
import { useOrchestrationStore } from '@/store/orchestrationStore';

const { Text } = Typography;

const App: React.FC = () => {
  const pageSizeDefault = 50;
  const { id, share_id } = useConfig();
  const router = useRouter();
  const [chatHistory, setChatHistory] = useState<any[]>([]);
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(pageSizeDefault);
  const [searchQuery, setSearchQuery] = useState('');
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [logoShow, setLogoShow] = useState(false);
  const containerRef = useRef(null);

  const { setLinkParams } = useConfigActions();
  const { isInOrchestrationPage } = useOrchestrationStore();



  useEffect(() => {
    debouncedGetHistoryData();
  }, [id, pageNum, searchQuery, pageSize]);

  // useEffect(() => {
  //   getHistoryData();
  // }, [id, pageNum, searchQuery, pageSize]);

  const getHistoryData = async () => {
    setLoading(true);
    try {

      if (id) {
        const today = new Date();
        today.setHours(23, 59, 59, 999);
        const start = new Date();
        start.setHours(0, 0, 0, 0);
        start.setDate(today.getDate() - 7);
        const historyData = await chatService.getHistories({
          appId: id,
          pageNum: pageNum,
          pageSize: pageSize,
          dateStart: start.toISOString(),
          dateEnd: today.toISOString(),
          q: searchQuery,
        });

        const updatedData = historyData?.data || [];

        if (updatedData.length < pageSize) {
          setHasMore(false);
        }

        const groupedByDate = updatedData.reduce((acc: any, item: any) => {
          const beijingTime = dayjs.utc(item.time).tz('Asia/Shanghai');
          const date = beijingTime.format('YYYY-MM-DD');
          const today = dayjs().tz('Asia/Shanghai').format('YYYY-MM-DD');

          const displayDate = date === today ? '今天' : date;

          if (!acc[date]) {
            acc[date] = { time: displayDate, child: [] };
          }
          acc[date].child.push(item);
          return acc;
        }, {} as { [key: string]: { time: string; child: any[] } });

        const result = Object.keys(groupedByDate).map((key) => groupedByDate[key]);

        if (pageNum === 1) {
          setChatHistory(result);
        } else {
          const mergedHistory = [...chatHistory, ...result].reduce((acc, item) => {
            const existingItem = acc.find((i: any) => i.time === item.time);
            if (existingItem) {
              existingItem.child.push(...item.child);
            } else {
              acc.push(item);
            }
            return acc;
          }, []);

          // 按日期排序
          mergedHistory.sort((a: any, b: any) => {
            const dateA = a.time === '今天' ? dayjs().format('YYYY-MM-DD') : a.time;
            const dateB = b.time === '今天' ? dayjs().format('YYYY-MM-DD') : b.time;
            return dayjs(dateB).diff(dayjs(dateA));
          });

          setChatHistory(mergedHistory);
        }
      }
    } catch (error) {
      console.error(error)
    } finally {
      setLoading(false);
    }
  };

  const debouncedGetHistoryData = debounce(getHistoryData, 300);

  const handleSearch = useCallback(
    debounce(() => {
      setPageNum(1);
      setPageSize(pageSizeDefault);
      setHasMore(true);
    }, 500),
    []
  );

  const onInputChange = (e) => {
    setSearchQuery(e.target.value);
    handleSearch();
  };

  // const handleSearch = (e) => {
  //   console.log(e.target.value)
  //   setSearchQuery(e.target.value || '');
  //   setPageNum(1);
  //   setPageSize(pageSizeDefault);
  //   setHasMore(true);
  // };


  const handleScroll = useCallback(() => {
    if (containerRef.current) {
      const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
      if (scrollHeight - scrollTop <= clientHeight + 100 && !loading && hasMore) {
        setLoading(true)
        setPageSize((prevPageSize) => prevPageSize + pageSizeDefault);
        // setPageNum((prevPageNum) => prevPageNum + 1);
      }
    }
  }, [loading, hasMore]);

  useEffect(() => {
    const container = containerRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll);
    }
    return () => {
      if (container) {
        container.removeEventListener('scroll', handleScroll);
      }
    };
  }, [handleScroll]);

  const { isPc } = useWindowWidth();

  return (
    <div
      className="w-full"
      style={{
        backgroundColor: '#EDF0F8',
        paddingBottom: '50px',
      }}
    >
      <div
        onClick={() => {
          setLogoShow(!logoShow);
        }}
      >
        {!isPc && <HeaderLogo />}
      </div>

      {(isPc || (!isPc && logoShow)) && <HomeMenuList />}

      <div
        className={`h-full w-full ${!isPc && 'overflow-auto [-ms-overflow-style:none] [scrollbar-width:none]'}`}
        ref={containerRef}
        style={{
          overflowY: 'auto',
          height: 'calc(100vh - 20px)',
        }}
      >
        <div
          className="mx-auto max-w-4xl"
          style={{
            width: isPc ? 'unset' : '80%',
          }}
        >
          <div className="sticky-header" style={{ paddingTop: '50px' }}>
            <div className="flex items-center justify-center">
              <h1 className="history-title text-2xl font-bold">历史会话</h1>
            </div>
            <div
              style={{
                paddingTop: '20px',
              }}
            >
              <Input
                placeholder="搜索最近7天历史会话..."
                allowClear
                prefix={<SearchOutlined className="text-gray-400" />}
                className="rounded-lg border-gray-200 py-2"
                style={{
                  borderRadius: '12px',
                  height: '55px',
                  border: '1px solid #E5E5E5'
                }}
                // value={searchQuery}
                // defaultValue={searchQuery}
                // onChange={handleSearch}
                onChange={onInputChange}
              />
            </div>
          </div>

          <div className="space-y-8">
            {chatHistory.map((day, dateIndex) => (
              <div key={dateIndex}>
                <div
                  className="mb-4 mt-4 text-sm"
                  style={{
                    fontSize: '24px',
                    fontWeight: '700',
                  }}
                >
                  {day.time}
                </div>
                <div>
                  {day.child.map((msg: any, msgIndex: number) => {
                    // const highlightText = (text: string, searchQuery: string, shouldRemoveRefTags: boolean = false) => {
                    //   if (!text) return null;

                    //   const processedText = shouldRemoveRefTags ? removeRefTags(text) : text;

                    //   return processedText.split(searchQuery).map((part: string, index: number) => (
                    //     index > 0 ? (
                    //       [<span style={{ color: '#2e67fa' }} key={index}>{searchQuery}</span>, part]
                    //     ) : part
                    //   ));
                    // };

                    // const highlightTitle = highlightText(msg.title, searchQuery);

                    return (<div
                      onClick={() => {
                        if (isInOrchestrationPage) {
                          // 在编排页面内打开
                          console.log(id, share_id, msg.id)
                          if (id && share_id) {
                            const searchParams = new URLSearchParams(location.search);
                            searchParams.set('chatId', msg.id);
                            setLinkParams({ id, share_id, chat_id: msg.id });
                            const event = new CustomEvent('orchestration-content-change', {
                              detail: { type: 'chat', id, share_id }
                            });
                            window.dispatchEvent(event);
                          }
                        } else {
                          router.push(`/apps/chat/${id}/${share_id}?chatId=${msg.id}`);
                        }
                        console.log(msg);
                        // router.push(`/apps/chat/${id}/${share_id}?chatId=${msg.id}`);
                      }}
                      key={msgIndex}
                      style={{
                        flexDirection: 'column',
                        alignItems: 'flex-start',
                        marginBottom: '8px'
                      }}
                      className="group relative flex cursor-pointer  rounded-lg bg-white p-2 transition-shadow hover:shadow-sm"
                    >
                      <div
                        className={`cursor-pointer justify-between hover:text-purple`}
                        style={{
                          width: '100%',
                          height: msg?.highlight_content ? 'unset' : '30px',
                          lineHeight: msg?.highlight_content ? 'unset' : '30px',
                          flex: 1,
                          overflow: 'hidden',
                          whiteSpace: 'nowrap',
                          textOverflow: 'ellipsis',
                          fontWeight: msg?.highlight_content ? '700' : 'unset',
                          display: 'flex',
                        }}
                      >
                        <div
                          style={{ marginRight: '5px' }}
                          className="flex items-center justify-center"
                        >
                          {' '}
                          📑
                          <div
                            id="highlight"
                            className="pl-2 text-gray-700"
                            style={{
                              width: isPc ? 'unset' : '200px',
                              flex: 1,
                              overflow: 'hidden',
                              whiteSpace: 'nowrap',
                              textOverflow: 'ellipsis',
                            }}
                            dangerouslySetInnerHTML={{ __html: removeRefTags(msg?.title) }}
                          >
                          </div>
                        </div>
                        <div className="group flex items-center">
                          <div
                            className="time flex-shrink-0 text-sm text-gray-400"
                            style={{ width: isPc ? '160px' : '60px' }}
                          >
                            {dayjs(msg.time).format(isPc ? 'YYYY-MM-DD HH:mm:ss' : 'HH:mm:ss')}
                          </div>
                        </div>
                      </div>
                      {msg?.highlight_content && (
                        <div
                          id="highlight"
                          style={{
                            width: '100%',
                            flex: 1,
                            overflow: 'hidden',
                            whiteSpace: 'nowrap',
                            textOverflow: 'ellipsis',
                            fontSize: '12px',
                            marginTop: '5px',
                          }}
                          dangerouslySetInnerHTML={{ __html: removeRefTags(msg?.highlight_content) }}
                        >
                        </div>
                      )}
                    </div>
                    )
                  })}
                </div>
              </div>
            ))}
          </div>
          {loading && (
            <div className="py-4 text-center">
              <Spin />
            </div>
          )}
          {!hasMore && <div className="py-4 text-center">没有更多数据了</div>}
        </div>
      </div>
    </div>
  );
};

export default App;
